package util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * Utility class for common File I/O operations.
 */
public final class FileIO {

	private FileIO() {}

	/**
	 * Uses Class.getResource() to get a URL, however throws an exception instead of
	 * returning null.
	 * @param path The location of the resource relative to the classpath
	 * @return A URL to the given path
	 * @throws IOException If resource is not found.
	 */
	public static URL getResource(String path) throws IOException{
		URL url = FileIO.class.getResource(path);

		if(url == null) {
			throw new IOException("Could not find resource located at " + path);
		}

		return url;
	}

	/**
	 * Uses Class.getResourceAsStream() to get an InputStream, however throws an exception instead of
	 * returning null.
	 * @param path The location of the resource relative to the classpath
	 * @return An InputStream of the given resource
	 * @throws IOException If resource is not found.
	 */
	public static InputStream getResourceAsStream(String path) throws IOException{
		InputStream is = FileIO.class.getResourceAsStream(path);

		if(is == null) {
			throw new IOException("Could not find resource located at " + path);
		}

		return is;
	}

	/**
	 * Gets the absolute path for the given resource whose path is relative to the classpath
	 * @param path Path to resource relative to the classpath.
	 * @return Path to resource from root.
	 * @throws IOException If resource is not found.
	 */
	public static String getAbsolutePath(String path) throws IOException {
		return getResource(path).toExternalForm();
	}

}
